package study.linkedlist;

public class SingleLinkedListDemo {
    public static void main(String[] args) {
        HeroNode hero1 = new HeroNode(1, "宋江", "及时雨");
        HeroNode hero2 = new HeroNode(2, "卢俊义","玉麒麟");
        HeroNode hero3 = new HeroNode(3, "吴用", "智多星");
        HeroNode hero4 = new HeroNode(4, "林冲","豹子头");

        SingleLinkedList singleLinkedList = new SingleLinkedList() ;
        singleLinkedList.add(hero1);
        singleLinkedList.add(hero2);
        singleLinkedList.add(hero3);
        singleLinkedList.add(hero4);

        //打印单链表
        singleLinkedList.list();
    }
}


//创建单链表
class SingleLinkedList {
    //创建头结点
    HeroNode head = new HeroNode(0, "", "");


    /**
     * 添加节点
     * 思路：当不考虑编号顺序时
     * 1. 找到当前链表的最后一个节点
     * 2. 将最后这个节点的next指向 新的节点
     */
    public void add(HeroNode heroNode) {
        //因为head不能动，我们需要找一个临时指针pointer
        HeroNode pointer = head;
        //找最后一个节点
        while (true) {
            //到达最后一个节点，终止遍历
            if (pointer.next == null){
                break;
            }
            //指针后移，寻找下一个节点
            pointer = pointer.next;
        }

        //将最后这个节点的next指向 新的节点
        pointer.next = heroNode;
    }

    public void list(){
        //判断链表是否为空
        if (head.next == null){
            System.out.println("链表为空");
            return;
        }
        HeroNode pointer = head.next;
        while (true) {
            if (pointer == null){
                break;
            }
            System.out.println(pointer);
            pointer = pointer.next;
        }
    }
}

//创建节点
class HeroNode {
    public int no;
    public String name;
    public String nickname;
    public HeroNode next;   //指向下一节点

    public HeroNode(int no, String name, String nickname) {
        this.no = no;
        this.name = name;
        this.nickname = nickname;
    }

    @Override
    public String toString() {
        return "HeroNode{" +
                "no=" + no +
                ", name='" + name + '\'' +
                ", nickname='" + nickname + '\'' +
                '}';
    }
}
